/*-
 * Copyright (c) 2009 Jonathan Anderson
 * All rights reserved.
 *
 * WARNING: THIS IS EXPERIMENTAL SECURITY SOFTWARE THAT MUST NOT BE RELIED
 * ON IN PRODUCTION SYSTEMS.  IT WILL BREAK YOUR SOFTWARE IN NEW AND
 * UNEXPECTED WAYS.
 * 
 * This software was developed at the University of Cambridge Computer
 * Laboratory with support from a grant from Google, Inc. 
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <QDebug> // TODO: tmp
#include <QMessageBox>

#include <sys/capability.h>

#include <errno.h>
#include <fcntl.h>

#include <iostream>
#include <sstream>

#include "cap.h"

#include "AccessDeniedException.h"
#include "Cache.h"
#include "Client.h"
#include "OpenFile.h"
#include "OperationCancelledException.h"
#include "UserAngel.h"

using namespace std;
using namespace userAngel;


QString OpenFile::argString() const
{
	QString str("path='" + path + "', flags=0");

	if(flags | O_WRONLY)  str += " | O_WRONLY";
	if(flags | O_RDWR)    str +=  " | O_RDWR";

	// TODO: other flags

	return str;
}

void OpenFile::readArguments(Client *client, userAngel::UserAngel::Datum d)
{
	int sock = client->socket();

	this->path = d.toString();
	this->flags = client->ua().recv().toInt();
	this->rights = client->ua().recv().toLong();
	this->umask = client->ua().recv().toInt();
}


void OpenFile::run(Client *client)
{
	File file;

	if(path.startsWith("/cap/"))
	{
		file = client->getFile(path);
		if(!file.isValid()) throw Exception("No such file");

		// what rights are being requested vs. what we have?
		cap_rights_t currentRights = file.rights();

		if(rights == currentRights) {}                        // equal
		else if((rights & currentRights) == rights)           // subset
		{
			int newFD = cap_new(file.fd(), rights);
			file = File(file.filename(), newFD, rights);
		}
		else if((rights & currentRights) == currentRights)    // superset
		{
			cap_rights_t additional = rights ^ currentRights;

			cap_rights_t write = CAP_WRITE | CAP_FSYNC | CAP_FTRUNCATE;
			if((additional & write) != additional)
				throw Exception("Access denied");

			// just want to convert to read-write
			if(!client->dbus().confirmOverwrite(file.filename()))
				throw AccessDeniedException("Overwriting '" + file.capName() + "'");

			int fd = cap_open(file.filename(), O_RDWR, rights, umask);
			file = File(file.filename(), fd, rights);
		}
		else throw Exception("Access denied");
	}
	else
	{
		int cap = cap_open(path, flags, rights, umask);
		file = File(path, cap, rights);
	}

	client->ua().send((int32_t) 1);
	client->ua().send(path, QList<int>() << file.fd());
}

